package com.cqc.web;

import com.cqc.common.Result;
import com.cqc.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author cui
 * @date 2025/3
 * 演示 DeferredResult
 **/
@Controller
@RequestMapping("product")
public class ProductController {

    private static final ConcurrentHashMap<String, DeferredResult<String>> orderMap = new ConcurrentHashMap<>();

    @Autowired
    ProductService productService;



    /**
     * http://localhost:8080/product/addOrder?orderId=1
     */
    @GetMapping("addOrder")
    @ResponseBody
    public DeferredResult<String> addOrder(String orderId) {
        DeferredResult<String> deferredResult = new DeferredResult<>(60000L);
        deferredResult.onTimeout(() -> {
            deferredResult.setResult("超时了");
        });
        deferredResult.onError(e -> {
            e.getMessage();
        });
        deferredResult.onCompletion(() -> {
            orderMap.remove(orderId);
        });
        orderMap.putIfAbsent(orderId, deferredResult);
        return deferredResult;
    }

    /**
     * http://localhost:8080/product/pay?orderId=1
     */
    @GetMapping("pay")
    @ResponseBody
    public DeferredResult<String> pay(String orderId) {
        DeferredResult<String> deferredResult = orderMap.get(orderId);
        deferredResult.setResult("支付完成，orderId=" + orderId);
        return deferredResult;
    }




}
